#include <iostream>
#include "log.hpp"
#include "InetAddr.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Common.hpp"

using namespace LogModule;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << argv[0] << " IP,port" << std::endl;
        exit(ExitCode::USAGE_ERR);
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    InetAddr peer(ip, port);
    int n = connect(sockfd, peer.GetSockaddr(), peer.Getlen());
    if (n < 0)
    {
        std::cerr << "connect cerr" << std::endl;
        exit(ExitCode::CONNECT_ERR);
    }

    while (true)
    {
        std::string input;
        std::cout << "Please input#";
        getline(std::cin, input);
        write(sockfd, input.c_str(), input.size());

        char buffer[1024];
        int n = read(sockfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "Server say:" << buffer << std::endl;
        }
    }

    close(sockfd);

    return 0;
}